﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Collections.Generic;

namespace AudioEffectBox
{
    public class Audio16BufferStream : Stream    
    {
        private const int BUFFER_SIZE = 220;
        private Queue<Stream> _internalSampleQueue;
        private MemoryStream _buffer;
        public Audio16BufferStream()
        {
            _internalSampleQueue = new Queue<Stream>();
            _buffer = null;
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanSeek
        {
            get { return false; }
        }

        public override bool CanWrite
        {
            get { return true; }
        }

        public override void Flush()
        {
            //do nothing
        }

        public override long Length
        {
            get { throw new NotImplementedException(); }
        }

        public override long Position
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override int Read(byte[] buffer, int offset, int count)
        {
            throw new NotImplementedException();
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotImplementedException();
        }

        public override void SetLength(long value)
        {
            throw new NotImplementedException();
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_buffer == null) _buffer = new MemoryStream();
            lock (_buffer)
            {
                _buffer.Write(buffer, offset, count);
                if (_buffer.Length >= BUFFER_SIZE)
                {
                    _buffer.Seek(0, SeekOrigin.Begin);
                    lock (_internalSampleQueue)
                    {
                        _internalSampleQueue.Enqueue(_buffer);
                    }
                    _buffer = null;
                }
            }
        }

        public Stream GetSamples()
        {
            lock (_internalSampleQueue)
            {
                if (_internalSampleQueue.Count > 0) return _internalSampleQueue.Dequeue();
                else
                    return null;
            }
        }
    }
}
